package cn.edu.zime.tjh.client;

import cn.edu.zime.tjh.handler.AsyncUDPClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.util.function.Consumer;

public class AsyncEchoUDPClient {
    private EventLoopGroup group;
    private Channel channel;
    private boolean isConnected = false;
    private InetSocketAddress serverAddress;
    
    private Consumer<String> messageCallback;
    private Consumer<String> statusCallback;
    
    public AsyncEchoUDPClient(Consumer<String> messageCallback, Consumer<String> statusCallback) {
        this.messageCallback = messageCallback;
        this.statusCallback = statusCallback;
    }
    
    public void connect(String host, int port) throws Exception {
        group = new NioEventLoopGroup();
        serverAddress = new InetSocketAddress(host, port);
        
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<NioDatagramChannel>() {
                        @Override
                        protected void initChannel(NioDatagramChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new AsyncUDPClientHandler(messageCallback, statusCallback));
                        }
                    });
            
            ChannelFuture f = b.bind(0).sync();
            channel = f.channel();
            isConnected = true;
            
            if (statusCallback != null) {
                statusCallback.accept("已连接到UDP服务器 " + host + ":" + port);
            }
            
        } catch (Exception e) {
            isConnected = false;
            if (statusCallback != null) {
                statusCallback.accept("连接失败: " + e.getMessage());
            }
            throw e;
        }
    }
    
    public void sendMessage(String message) {
        if (channel != null && isConnected) {
            try {
                ByteBuf buf = channel.alloc().buffer();
                buf.writeCharSequence(message, CharsetUtil.UTF_8);
                DatagramPacket packet = new DatagramPacket(buf, serverAddress);
                
                channel.writeAndFlush(packet).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            if (statusCallback != null) {
                                statusCallback.accept("消息发出");
                            }
                        } else {
                            if (statusCallback != null) {
                                statusCallback.accept("消息发送失败: " + future.cause().getMessage());
                            }
                        }
                        // UDP是无连接协议，发送操作成功只表示数据包已发出，不表示对方已收到
                        // 因此不显示"发送成功"提示
                    }
                });
            } catch (Exception e) {
                if (statusCallback != null) {
                    statusCallback.accept("发送消息时出错: " + e.getMessage());
                }
            }
        }
    }
    
    public void disconnect() {
        isConnected = false;
        if (channel != null) {
            channel.close();
        }
        if (group != null) {
            group.shutdownGracefully();
        }
        if (statusCallback != null) {
            statusCallback.accept("已断开UDP连接");
        }
    }
    
    public boolean isConnected() {
        return isConnected && channel != null && channel.isActive();
    }
}